<template>
  <div class="image-to-comic">
    <!--    <h2>图像转漫画</h2>-->

    <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop="handleDrop">
      <input type="file" ref="fileInput" @change="handleFileChange" accept="image/*" style="display: none;">

      <div v-if="!uploadedImage" class="upload-prompt">
        <p>点击或拖拽图片到这里上传</p>
      </div>

      <div v-else class="image-preview">
        <img :src="uploadedImage" alt="上传的图片">
        <button @click.stop="removeImage" class="remove-btn">×</button>
      </div>
    </div>

    <div class="style-selector">
      <label>选择漫画风格:</label>
      <select v-model="selectedStyle">
        <option v-for="style in styles" :value="style.value" :key="style.value">
          {{ style.label }}
        </option>
      </select>
    </div>

    <button @click="convertToComic" :disabled="!uploadedImage || isConverting">
      {{ isConverting ? '转换中...' : '转换为漫画' }}
    </button>


    <div v-if="description.length >= 0" class="默认风格" v-for="(url, index) in image_urls">
      <p class="description">{{ description[index] }}</p>
      <div class="comic-panels">
        <img
            :key="index"
            :src="url"
            alt="漫画面板">
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

const image_synthesis_url = '/api/v1/services/aigc/text2image/image-synthesis'
const image_to_comic = "/api/image-to-comic"
export default {
  data() {
    return {
      uploadedImage: null,
      selectedStyle: 'default',
      styles: [
        {value: 'default', label: '默认风格'},
        {value: 'black-white', label: '少年漫画'},
        {value: 'watercolor', label: '少女漫画'},
        {value: 'pop-art', label: '青年漫画'},
        {value: 'pop1-art', label: '青年漫画'}
      ],
      isConverting: false,
      convertedImage: null,
      image_urls: [],
      description: []
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        this.previewImage(file);
      }
    },
    handleDrop(e) {
      e.preventDefault();
      const file = e.dataTransfer.files[0];
      if (file && file.type.match('image.*')) {
        this.previewImage(file);
      }
    },
    previewImage(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.uploadedImage = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    removeImage() {
      this.uploadedImage = null;
      this.$refs.fileInput.value = '';
    },
    async convertToComic() {
      if (!this.uploadedImage) return;

      this.isConverting = true;

      try {
        const formData = new FormData();
        const blob = await fetch(this.uploadedImage).then(r => r.blob());

        formData.append('image', blob, 'uploaded-image.png');
        formData.append('style', this.selectedStyle);

        const response = await axios.post(image_to_comic, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });


        const descriptions = response.data.descriptions
        console.log(descriptions)


        let prompts = ""
        for (let i = 0; i < descriptions.length; i++) {
          const prompt = descriptions[i]
          prompts = prompts + "\n" + `第${i + 1}个画面：` + prompt + "\n"
        }

        for (let i = 0; i < descriptions.length; i++) {
          this.description.push(descriptions[i]);

          const prompt = descriptions[i] + `现在绘制第${i + 1}个画面`


          const imageResp = await axios.post(
              image_synthesis_url,
              {
                prompt: prompt,
                style: 'anime',
              },
              {
                headers: {
                  'Content-Type': 'application/json',
                }
              }
          );
          const url = await imageResp.data.url;
          this.image_urls.push(url)
        }


      } catch (error) {
        console.error('转换失败:', error);
        alert('图片转换失败，请重试');
      } finally {
        this.isConverting = false;
      }
    }
  }
}
</script>

<style scoped>
.image-to-comic {
  padding: 20px;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  margin-bottom: 15px;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.upload-area:hover {
  border-color: #999;
}

.upload-prompt p {
  margin: 0;
  color: #666;
}

.image-preview {
  position: relative;
  max-width: 100%;
}

.image-preview img {
  max-width: 100%;
  max-height: 300px;
  display: block;
  margin: 0 auto;
}

.remove-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #ff4444;
  color: white;
  border: none;
  border-radius: 50%;
  width: 25px;
  height: 25px;
  font-size: 14px;
  cursor: pointer;
}

.style-selector {
  margin-bottom: 15px;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
}

.result {
  margin-top: 20px;
  text-align: center;
}

.result img {
  max-width: 100%;
  max-height: 400px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.download-btn {
  display: inline-block;
  background-color: #2196F3;
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  text-decoration: none;
}


button {
  width: 100%;
  background-color: #4CAF50;
  color: white;
  padding: 12px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.results {
  width: 100%;
  margin-top: 20px;
}

.comic-panels {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  width: 100%;
}

.comic-panels img {
  width: 100%;
  height: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.description {
  width: 100%;
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comic-panels {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 480px) {
  .comic-panels {
    grid-template-columns: 1fr;
  }

  textarea {
    height: 120px;
  }
}
</style>